package net.osin.crypto

import java.io.IOException

import scala.collection.mutable.ArrayBuffer

object Exchange {
  def toByteArray(i: Int): Array[Byte] = {
    val byteArray: Array[Byte] = new Array[Byte](4)
    byteArray(0) = (i >>> 24).toByte
    byteArray(1) = ((i & 0xFFFFFF) >>> 16).toByte
    byteArray(2) = ((i & 0xFFFF) >>> 8).toByte
    byteArray(3) = (i & 0xFF).toByte
    byteArray
  }

  /**
   * 字节数组拼接
   *
   * @param params
   * @return
   */
  def join(params: Array[Byte]*) = {
    val baos = new ArrayBuffer[Byte]()
    var res:Array[Byte] = null
    try {
      for (i <- 0 until params.length) {
        baos.appendAll(params(i))
      }
      res  = baos.toArray
    } catch {
      case e: IOException =>
        e.printStackTrace()
    }
    res
  }

  def byteArrayToHexString(b: Array[Byte]): String = toHexFromBytes(b) // b.map("%02x".format(_)).mkString

  val hexSymbols = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")

  val BITS_PER_HEX_DIGIT = 4

  def toHexFromByte(b: Byte): String = {
    val leftSymbol = ((b >>> BITS_PER_HEX_DIGIT) & 0x0f).toByte
    val rightSymbol = (b & 0x0f).toByte
    hexSymbols(leftSymbol) + hexSymbols(rightSymbol)
  }
  def toHexFromBytes(bytes: Array[Byte]): String = {
    if (bytes == null || bytes.length == 0) return ""
    // there are 2 hex digits per byte
    // 每个byte有两个hex字符
    // 创建一个缓冲区来存放这个内容
    val hexBuffer = new StringBuilder(bytes.length * 2)
    // for each byte, convert it to hex and append it to the buffer
    // 然后操作每一个byte, 把他转换成hex后添加到缓冲区中.
    bytes.foreach(b => hexBuffer.append(toHexFromByte(b)))
    hexBuffer.toString
  }

}
